use super::Data;
use leptos::*;
use std::{collections::HashMap, rc::Rc};

#[allow(non_snake_case)]
#[component]
pub fn Digit(label: &'static str, #[prop(into)] name: String) -> impl IntoView {
    let (getter, setter) = use_context::<(
        ReadSignal<HashMap<String, Data>>,
        WriteSignal<HashMap<String, Data>>,
    )>()
    .expect("to have found the setter provided");
    let field = Rc::new(name);
    let value = {
        let field = Rc::clone(&field);
        move || {
            let map = getter.get();
            map.get(field.as_ref())
                .and_then(|v| v.num())
                .unwrap_or_default()
        }
    };
    view! {
        <div
            class="flex flex-col gap-1 py-2"
        >
            <label class="pl-2 text-lg">{label}":"</label>
            <input
                class="border-solid border rounded h-9 outline-blue-400 pl-2"
                value = move || { value() }
                type="number"
                on:change=move |ev| {
                    let val = event_target_value(&ev);
                    let key = field.as_ref().to_string();
                    setter
                        .update(|map| {
                            let val = val.parse::<f64>().unwrap_or_default();
                            let val = Data::Number(val);
                            map.insert(key, val);
                        })
                }
            />
        </div>
    }
}
